package com.itheima.appserver.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.appserver.exception.BusinessException;
import com.itheima.appserver.interceptor.UserHandler;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.dubbo.api.*;
import com.itheima.model.domain.Question;
import com.itheima.model.domain.UserInfo;
import com.itheima.model.dto.RecommendUserDto;
import com.itheima.model.mongo.RecommendUser;
import com.itheima.model.vo.ErrorResult;
import com.itheima.model.vo.NearUserVo;
import com.itheima.model.vo.PageResult;
import com.itheima.model.vo.TodayBest;
import com.itheima.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate template;

    @Value("${tanhua.default.recommend.users}")
    private String users;//读取配置文件的信息

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserLocationApi userLocationApi;

    @Autowired
    private MessagesService messagesService;

    //查询今日佳人数据
    public TodayBest todayBest() {
        //1、获取用户id
        Long userId = UserHandler.getId();
        //2、调用API查询
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        //3、将RecommendUser转化为TodayBest对象
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        //4、返回
        return vo;
    }

    public PageResult recommendation(RecommendUserDto dto) {
        //1、获取用户id
        Long userId = UserHandler.getId();
        //2、调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
        PageResult pr = recommendUserApi.pagerec(dto.getPage(), dto.getPagesize(), userId);
        //3、获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //4、判断列表是否为空
        if (items == null || items.size() <= 0) {
            return pr;
        }
        //5、提取所有推荐的用户id列表
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        UserInfo userInfo = new UserInfo();
        userInfo.setAge(dto.getAge());
        userInfo.setGender(dto.getGender());
        //6、构建查询条件，批量查询所有的用户详情
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
        //7、循环推荐的数据列表，构建vo对象
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info != null) {
                TodayBest vo = TodayBest.init(info, item);
                list.add(vo);
            }
        }
        //8、构造返回值
        pr.setItems(list);
        return pr;
    }

    //查看佳人信息
    public TodayBest findbest(Long userId) {
        //查询用户详情
        UserInfo info = userInfoApi.findById(userId);
        //查询两者之间的推荐值
        RecommendUser recommendUser = recommendUserApi.findbest(userId, UserHandler.getId());
        //返回数据
        TodayBest init = TodayBest.init(info, recommendUser);
        return init;
    }

    //查询陌生人问题
    public String findQue(Long userId) {
        Question question = questionApi.findById(userId);
        return question == null ? "你喜欢谁?" : question.getTxt();
    }

    public void replyQuestions(Long userId, String reply) {
        //获取当前用户id
        Long id = UserHandler.getId();
        //根据id查询用户详情信息
        UserInfo userInfo = userInfoApi.findById(id);
        //构造信息
        Map map = new HashMap<>();
        map.put("userId", id);
        map.put("huanXinId", Constants.HX_USER_PREFIX + id);
        map.put("nickname", userInfo.getNickname());
        map.put("strangerQuestion", findQue(userId));
        map.put("reply", reply);
        //转化为string
        String message = JSON.toJSONString(map);
        System.out.println(message);
        //调用temp发送
        Boolean aBoolean = template.sendMsg(Constants.HX_USER_PREFIX + userId, message);
        System.out.println(userId);
        System.out.println(aBoolean);
        if (!aBoolean) {
            throw new BusinessException(ErrorResult.error());
        }
    }

    //左滑右滑
    public List<TodayBest> cards() {
        //调用api查询数据,数量限制
        List<RecommendUser> list = recommendUserApi.cards(UserHandler.getId(), 10);
        //判断是否为空,为空构造默认数据
        if (CollUtil.isEmpty(list)) {
            list = new ArrayList<>();
            //根配置文件的数据进行处理
            String[] userIds = users.split(",");
            for (String userId : userIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(userId));
                recommendUser.setToUserId(UserHandler.getId());
                recommendUser.setScore(RandomUtil.randomDouble(60, 90));
                list.add(recommendUser);
            }
        }
        //不为空构造vo对象
        List<TodayBest> vos = new ArrayList<>();
        //查询用户详情信息
        //获取用户id
        List<Long> ids = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, null);
        //遍历获取vo对象
        for (RecommendUser recommendUser : list) {
            UserInfo info = map.get(recommendUser.getUserId());
            if (info != null) {
                TodayBest vo = TodayBest.init(info, recommendUser);
                vos.add(vo);
            }
        }
        //返回数据
        return vos;
    }
    //喜欢
    public void love(Long likeUserId) {
        //调用api保存数据
        Boolean love = userLikeApi.love(UserHandler.getId(), likeUserId, true);
        //判断是否保存成功
        if (!love) {
            throw new BusinessException(ErrorResult.error());
        }
        //操作redis,写入喜欢的数据,删除不喜欢的数据
        redisTemplate.opsForSet().add(Constants.USER_LIKE_KEY + UserHandler.getId(), likeUserId.toString());
        redisTemplate.opsForSet().remove(Constants.USER_NOT_LIKE_KEY + UserHandler.getId(), likeUserId.toString());
        //判断是否双向喜欢,是的话就需要早好友表里添加双向关系
        String key = Constants.USER_LIKE_KEY + UserHandler.getId();
        Boolean member = redisTemplate.opsForSet().isMember("key", likeUserId.toString());
        if (member) {
            messagesService.contacts(likeUserId);
        }
    }

    //不喜欢
    public void unlove(Long likeUserId) {
        //保存数据
        Boolean love = userLikeApi.love(UserHandler.getId(), likeUserId, false);
        if (!love) {
            throw new BusinessException(ErrorResult.error());
        }
        //2、操作redis，写入喜欢的数据，删除不喜欢的数据 (喜欢的集合，不喜欢的集合)
        redisTemplate.opsForSet().remove(Constants.USER_LIKE_KEY + UserHandler.getId(), likeUserId.toString());
        redisTemplate.opsForSet().add(Constants.USER_NOT_LIKE_KEY + UserHandler.getId(), likeUserId.toString());
        //判断是否双向喜欢,是的话就需要在好友表里删双向关系

    }

    //搜附近
    public List<NearUserVo> search(String gender, String distance) {
        //调用api查询当前用户附近用户
        List<Long> ids = userLocationApi.search(UserHandler.getId(), Double.valueOf(distance));
        //判断是否为空
        if (CollUtil.isEmpty(ids)) {
            return new ArrayList<>();
        }
        //不为空,查询用户的详情信息,并设置过滤条件
        UserInfo userInfo = new UserInfo();
        userInfo.setGender(gender);
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids, userInfo);
        //创建返回vo集合对象
        List<NearUserVo> vos = new ArrayList<>();
        //遍历ids
        for (Long id : ids) {
            //排除当前用户id
            if (id == UserHandler.getId()) {
                continue;
            }
            UserInfo info = map.get(id);
            if (info != null) {
                NearUserVo vo = NearUserVo.init(info);
                vos.add(vo);
            }
        }
        return vos;
    }
}